import { Button, Input } from 'antd'
import React, { useEffect, useState, useCallback } from 'react'
import type { ChangeEvent, KeyboardEvent } from 'react'
import { Outlet } from 'react-router-dom'
import { getCaptcha,login } from './service'
import type {ResponseType} from '@/interface/core/entity'
import type {LoginRequest,LoginResponse} from './typings'
import storage from '@/utils/storage'
import ApiPrefix from '@/config/prefix'

const Page: React.FC = () => {
  const [username, setUsername] = useState<string>('')
  const [password, setPassword] = useState<string>('')
  const [captcha, setCaptcha] = useState<string>('')
  const [imgSrc, setImgSrc] = useState<string>('')
  const handleChangeUsername = (event: ChangeEvent) => {
    setUsername((event.target as HTMLInputElement).value)
  }
  const handleChangePwd = (event: ChangeEvent) => {
    setPassword((event.target as HTMLInputElement).value)
  }
  const handleChangeCaptcha = (event: ChangeEvent) => {
    setCaptcha((event.target as HTMLInputElement).value)
  }
  //   const handleChangeUsername=(event: ChangeEvent)=>{
  //     setUsername((event.target as HTMLInputElement).value)
  //   }
  const handleGetImg = () => {
    getCaptcha().then((res) => {
      if (res) {
        setImgSrc('data:image/png;base64,'+res?.data)
      }
    })
  }

  const handleLogin=()=>{
    login({
      userName: username,
      userPwd: password,
      verifyCode: captcha
    }).then((res:ResponseType<LoginResponse>)=>{
      if(res?.code==0){
        storage.set(ApiPrefix.tokenPrefix,res?.data?.projToken)
        window.location.href='/'
      }else{
        alert(res?.message)
      }
    }).catch(res=>{
      console.log(res)
    })
  }
  const handleKeydownEvent=(event:KeyboardEvent)=>{
    if(event.key=='Enter'){
      handleLogin()
    }
  }
  useEffect(() => {
    handleGetImg()
  }, [])
  return (
    <>
      <div style={{ width: '300px' }}>
        <div>
          <span>账号：</span>
          <Input type="text" value={username} onChange={handleChangeUsername} onKeyDownCapture={handleKeydownEvent}/>
        </div>
        <div>
          <span>密码：</span>
          <Input type="password" value={password} onChange={handleChangePwd}  onKeyDownCapture={handleKeydownEvent}/>
        </div>
        <div>
          <span>验证码：</span>
          <Input value={captcha} onChange={handleChangeCaptcha} onKeyDownCapture={handleKeydownEvent}/>
          <img
            alt=""
            style={{ verticalAlign: 'top', height: '100%', width: '100%' }}
            src={imgSrc}
            onClick={handleGetImg}
          />
        </div>
      </div>
      <Button onClick={handleLogin}>登陆</Button>
    </>
  )
}

export default Page
